package com.mall.shopping.services;

import com.alibaba.fastjson.JSON;
import com.mall.shopping.IProductCateService;
import com.mall.shopping.constant.GlobalConstants;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ProductCateConverter;
import com.mall.shopping.dal.entitys.ItemCat;
import com.mall.shopping.dal.persistence.ItemCatMapper;
import com.mall.shopping.dto.AllProductCateRequest;
import com.mall.shopping.dto.AllProductCateResponse;
import com.mall.shopping.dto.ProductCateDto;
import com.mall.shopping.services.cache.CacheManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author:tanxin Desc:
 * @date:2020/7/11 9:11
 */
@Slf4j
@Component
@Service
public class ProductCateServiceImpl implements IProductCateService {

    @Resource
    ItemCatMapper itemCatMapper;
    @Resource
    ProductCateConverter cateConverter;
    @Resource
    CacheManager cacheManager;
    @Override
    public AllProductCateResponse getAllProductCate(AllProductCateRequest request) {
        AllProductCateResponse response = new AllProductCateResponse();
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        //查询是否有缓存
        String json = cacheManager.checkCache(generatorProductCateCache(request));
        if(StringUtils.isNotBlank(json)){
            List<ProductCateDto> productCateDtos = JSON.parseArray(json, ProductCateDto.class);
            cacheManager.expire(generatorProductCateCache(request),GlobalConstants.PRODUCT_ITEM_EXPIRE_TIME);
            response.setProductCateDtoList(productCateDtos);
            return response;
        }
        List<ItemCat> itemCats = itemCatMapper.selectAll();
        try {
            //检查排序方式,未写
          //  request.requestCheck();
            if (itemCats.isEmpty()){
                response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            }
            List<ProductCateDto> productCateDtoList = cateConverter.items2Dto(itemCats);
            response.setProductCateDtoList(productCateDtoList);
            cacheManager.setCache(GlobalConstants.PRODUCT_CATE_CACHE_KEY,JSON.toJSON(productCateDtoList).toString(),
                    GlobalConstants.PRODUCT_CATE_EXPIRE_TIME);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
    //产生商品分类缓存key
    private String generatorProductCateCache(AllProductCateRequest request){
        return GlobalConstants.PRODUCT_CATE_CACHE_KEY;
    }
}
